package com.milloc.db.service.impl;

import com.milloc.db.dto.PageDTO;
import com.milloc.db.dto.PageOutDTO;
import com.milloc.db.entity.ScriptEntity;
import com.milloc.db.repository.ScriptEntityRepository;
import com.milloc.db.service.ScriptService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.milloc.db.util.SQLUtils.PREDICATE_ARRAY;
import static com.milloc.db.util.SQLUtils.like;

/**
 * @author gongdeming
 * @create 2019-08-27
 */
@Service
public class ScriptServiceImpl implements ScriptService {
    private final ScriptEntityRepository scriptEntityRepository;

    public ScriptServiceImpl(ScriptEntityRepository scriptEntityRepository) {
        this.scriptEntityRepository = scriptEntityRepository;
    }

    @Override
    public ScriptEntity save(ScriptEntity scriptEntity) {
        return scriptEntityRepository.saveAndFlush(scriptEntity);
    }

    @Override
    public void remove(String scriptEntityId) {
        scriptEntityRepository.deleteById(scriptEntityId);
    }

    @Override
    public PageOutDTO<ScriptEntity> listAll(String scriptEntityId, String keyword, PageDTO pageDTO) {
        Page<ScriptEntity> res = scriptEntityRepository.findAll((root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (scriptEntityId != null) {
                predicates.add(builder.equal(root.get("id"), scriptEntityId));
            }

            if (StringUtils.isNotBlank(keyword)) {
                String aKeyWord = like(keyword);
                Predicate nameLike = builder.like(root.get("name"), aKeyWord);
                Predicate descriptionLike = builder.like(root.get("description"), aKeyWord);
                predicates.add(builder.or(nameLike, descriptionLike));
            }
            return builder.and(predicates.toArray(PREDICATE_ARRAY));
        }, pageDTO.pageRequest());
        return PageOutDTO.from(res);
    }

    @Override
    public ScriptEntity fetchOne(String scriptEntityId) {
        return scriptEntityRepository.getOne(scriptEntityId);
    }
}
